package com.weseal.utils;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author weseal
 * @title
 * @description
 * @usage
 * @copyright Copyright 2014  rrmj Corporation. All rights reserved.
 * @company 上海众多美网络科技有限公司
 * @create 2017/10/30
 */
public class MasterCredentials extends SimpleCredentialsMatcher {

	private Cache<String, AtomicInteger> passwordRetryCache;

	public MasterCredentials(CacheManager cacheManager) {
		this.passwordRetryCache = cacheManager.getCache("passwordRetryCache");
	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		String loginName = (String) token.getPrincipal();
		AtomicInteger retryCount = passwordRetryCache.get(loginName);
		if (null == retryCount) {
			retryCount = new AtomicInteger(0);
			passwordRetryCache.put(loginName, retryCount);
		}
		if (retryCount.incrementAndGet() > 5) {
			throw new ExcessiveAttemptsException();
		}
		passwordRetryCache.remove(loginName);
		return true;

	}
}
